package web

import (
	"JK-Junior-Go-Engineer-Camp/webook/internal/domain"
	"JK-Junior-Go-Engineer-Camp/webook/internal/service"
	"JK-Junior-Go-Engineer-Camp/webook/internal/web/jwt"
	"JK-Junior-Go-Engineer-Camp/webook/pkg/logger"
	"github.com/gin-gonic/gin"
)

// ArticleHandler 处理与帖子有关的请求
type ArticleHandler struct {
	svc service.ArticleService
	l   logger.LoggerV1
}

func NewArticleHandler(svc service.ArticleService, l logger.LoggerV1) *ArticleHandler {
	return &ArticleHandler{svc: svc, l: l}
}

// RegisterRoutes 注册路由
func (h *ArticleHandler) RegisterRoutes(server *gin.Engine) {
	g := server.Group("/articles")
	g.POST("/edit", h.Edit)
	g.POST("/publish", h.Publish)
}

// Edit 设计：接收Article输入，返回帖子ID
// 帖子的新建和编辑
func (h *ArticleHandler) Edit(ctx *gin.Context) {
	type Req struct {
		Id      int64  `json:"id"`
		Title   string `json:"title"`
		Content string `json:"content"`
	}
	var req Req
	if err := ctx.Bind(&req); err != nil {
		return
	}
	uc := ctx.MustGet("user").(jwt.UserClaims)
	artId, err := h.svc.Save(ctx, domain.Article{
		Id:      req.Id,
		Title:   req.Title,
		Content: req.Content,
		Author: domain.Author{
			Id: uc.UserId,
		},
	})
	if err != nil {
		ctx.JSON(200, Result{
			Code: 5,
			Msg:  "系统错误",
		})
		h.l.Error("保存文章失败",
			logger.Int64("userId", uc.UserId),
			logger.Error(err))
		return
	}
	ctx.JSON(200, Result{
		Data: artId,
	})
}

// Publish 帖子的发布
func (h *ArticleHandler) Publish(ctx *gin.Context) {
	type Req struct {
		Id      int64  `json:"id"`
		Title   string `json:"title"`
		Content string `json:"content"`
	}
	var req Req
	if err := ctx.Bind(&req); err != nil {
		return
	}
	uc := ctx.MustGet("user").(jwt.UserClaims)
	artId, err := h.svc.Publish(ctx, domain.Article{
		Id:      req.Id,
		Title:   req.Title,
		Content: req.Content,
		Author: domain.Author{
			Id: uc.UserId,
		},
	})
	if err != nil {
		ctx.JSON(200, Result{
			Code: 5,
			Msg:  "系统错误",
		})
		h.l.Error("发表文章失败",
			logger.Int64("userId", uc.UserId),
			logger.Error(err))
		return
	}
	ctx.JSON(200, Result{
		Data: artId,
	})
}
